package org.mindrive.system.service.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.mindrive.system.collection.system.PermissionEntity;
import org.mindrive.system.collection.system.UserEntity;
import org.mindrive.system.dao.PermissionDao;
import org.mindrive.system.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PermissionService extends BaseService {

    @Autowired
    private PermissionDao permissionDao;

    public List<Map<String, Object>> tree() {
        UserEntity loginUser = getLoginUser();
        String systemCode = "";

        QueryWrapper<PermissionEntity> query = new QueryWrapper<PermissionEntity>();
        query.ne("menu_type", "1").eq("system_code", systemCode);
        query.orderByAsc("sort_no");
        List<PermissionEntity> permissions = permissionDao.list(query);
        List<Map<String, Object>> tree = getPermissionIteration("", permissions);
        return tree;
    }

    private List<Map<String, Object>> getPermissionIteration(String parentId, List<PermissionEntity> all) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (PermissionEntity permission : all) {
            if (permission.getParentId().equals(parentId)) {
                Map<String, Object> item = new HashMap<String, Object>();
                item.put(TREE_KEY, permission.getId());
                item.put(TREE_TITLE, permission.getTitle());
                List<Map<String, Object>> children = getPermissionIteration(permission.getId(), all);
                if (children.size() == 0) {
                    item.put(TREE_IS_LEAF, true);
                } else {
                    item.put(TREE_CHILDREN, children);
                }
                result.add(item);
            }

        }
        return result;
    }

}
